"use strict";
/**
 * 关注事件服务
 * Created by liamjung on 2018/6/25.
 */
const {getWechatApi} = require("@libfintech/api-gateway-core/util/wechat_api_util");
const AbstractService = require("../abstract_service");

class SubscribeService extends AbstractService {

    async execute(wxMsg, mpConfig, pipeline) {

        let openId = wxMsg.FromUserName;

        let api = await getWechatApi(mpConfig);

        api.logger = pipeline.logger;
        // 获取微信用户基本信息
        let user = await api.getUser({
            openid: openId,
            lang: "zh_CN"
        });

        if (user) {
            //处理关注的用户

            //TODO 集成调试机制
            let accountSessionId;// = DebugUtil.getAccountSessionId(wxMessage.getEventKey());

            if (accountSessionId) {
                //扫码关注后，调试时，推送微信消息

                // DebugUtil.sendDebugMsg(this.mpService, accountSessionId, config, openId, this.debugAuthenticationUrl, DebugMsgTypeEnum.START_DEBUG);
            } else {
                let config = super.getRouteConfig(mpConfig, "subscribe");

                let createTime = +wxMsg.CreateTime;

                //SubscribeDTO
                let dto = {
                    subjectId: mpConfig.subjectId,
                    openId: openId,
                    mpId: mpConfig.mpId,
                    createTime: createTime,

                    nickname: user.nickname,
                    sex: user.sex === 1 ? "男" : (user.sex === 2 ? "女" : "未知"),
                    language: user.language,
                    city: user.city,
                    province: user.province,
                    country: user.country,
                    headImgUrl: user.headimgurl,
                    subscribeTime: user.subscribe_time,
                    //TODO 待测试
                    unionId: user.unionid,
                    sexId: user.sex,
                    remark: user.remark,
                    groupId: user.groupid,
                    tagIds: user.tagid_list,
                    //TODO 待测试
                    sceneId: wxMsg.EventKey === "" ? undefined : +wxMsg.EventKey.replace("qrscene_", "")
                };

                super.updateRequest(pipeline.request, config, dto);
            }
        }
    }
}

module.exports = new SubscribeService();